#!/bin/bash

echo "=== MES服务一键启动脚本 ==="

# 切换到项目目录
cd /home/ubuntu/zlymes/mesmaster
echo "切换到项目目录: $(pwd)"

# 激活conda环境
echo "激活conda环境..."
export PATH="/home/ubuntu/miniconda3/bin:$PATH"
source ~/miniconda3/etc/profile.d/conda.sh
conda activate mes

# 检查Django环境
echo "检查Django环境..."
python -c "import django; print('Django版本:', django.VERSION)" || {
    echo "Django环境检查失败！"
    exit 1
}

# 停止可能存在的旧服务
echo "停止旧服务..."
pkill -f "python manage.py runserver" 2>/dev/null || true
sleep 2

# 启动基础MES服务
echo "启动基础MES服务 (端口 8004)..."
nohup python manage.py runserver 0.0.0.0:8004 --settings=settings_mes_basic > /tmp/mes_8004.log 2>&1 &
sleep 3

# 启动完整MES服务
echo "启动完整MES服务 (端口 8005)..."
nohup python manage.py runserver 0.0.0.0:8005 --settings=settings_full_mes > /tmp/mes_8005.log 2>&1 &
sleep 3

# 启动Django管理服务
echo "启动Django管理服务 (端口 8006)..."
nohup python manage.py runserver 0.0.0.0:8006 --settings=settings_django_with_mes > /tmp/mes_8006.log 2>&1 &
sleep 3

# 检查服务状态
echo ""
echo "=== 检查服务状态 ==="
ps aux | grep "python manage.py runserver" | grep -v grep

echo ""
echo "=== 检查端口占用 ==="
for port in 8004 8005 8006; do
    if lsof -t -i:$port > /dev/null 2>&1; then
        echo "✓ 端口 $port 服务正在运行"
    else
        echo "✗ 端口 $port 服务未运行"
    fi
done

echo ""
echo "=== 服务访问地址 ==="
echo "- 基础MES服务: http://175.27.138.86:8004/"
echo "- 基础MES管理后台: http://175.27.138.86:8004/admin/"
echo "- 完整MES服务: http://175.27.138.86:8005/"
echo "- 完整MES管理后台: http://175.27.138.86:8005/admin/"
echo "- Django管理服务: http://175.27.138.86:8006/admin/"
echo ""
echo "管理员账户: admin / admin123"
echo ""
echo "日志文件位置:"
echo "- /tmp/mes_8004.log"
echo "- /tmp/mes_8005.log"
echo "- /tmp/mes_8006.log"
echo ""
echo "如果服务启动失败，请查看日志文件:"
echo "tail -f /tmp/mes_8004.log"
echo ""
echo "停止所有服务:"
echo "pkill -f 'python manage.py runserver'"
echo ""
echo "=== 启动完成 ===" 